package de.zainodis.kitchengnome.ui.adapter;

import android.content.Context;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import de.zainodis.commons.LogCat;
import de.zainodis.kitchengnome.R;
import de.zainodis.kitchengnome.domainmodel.ItemList;
import de.zainodis.kitchengnome.domainmodel.ListItem;

public class ItemListAdapter extends SortableListAdapter {

	private static final String TAG = "ItemListAdapter";

	private ItemList itemList;
	private LayoutInflater layoutInflater;

	public ItemListAdapter(Context context, ItemList entries) {
		this.itemList = entries;
		this.layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		sort();
	}

	@Override
	public int getCount() {
		return itemList != null ? itemList.getItems().size() : 0;
	}

	@Override
	public Object getItem(int position) {
		return itemList.getItems().get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = convertView;
		if (convertView == null) {
			view = layoutInflater.inflate(R.layout.layout_list_row, null);
		}

		// Retrieve item at given position
		ListItem entry = itemList.getItems().get(position);

		// Set name of item
		TextView nameField = (TextView) view.findViewById(R.id.layout_list_row_name);
		nameField.setText(entry.getName());

		if (entry.isDone()) {
			nameField.setPaintFlags(nameField.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
		} else {
			nameField.setPaintFlags(nameField.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
		}

		return view;
	}

	public void add(ListItem item) {
		itemList.getItems().add(item);
		sort();
	}

	public void delete(ListItem item) {
		itemList.getItems().remove(item);
		sort();
	}

	public ListItem delete(int position) {
		ListItem deleted = itemList.getItems().remove(position);
		sort();
		return deleted;
	}

	public void update(ItemList newList) {
		if (newList == null) {
			LogCat.e(TAG, "Failed to update list, as updated list is null.");
		} else {
			this.itemList = newList;
			sort();
		}
	}

	public ItemList getList() {
		return itemList;
	}

	public long getListId() {
		return itemList.getId();
	}

	public void clearDone() {
		if (itemList != null) {
			itemList.clearDone();
			if (!sort()) {
				notifyDataSetChanged();
			}
		}
	}

	public void clearList() {
		if (itemList != null) {
			itemList.clear();
		}
		// No need to sort, just reload the data set
		notifyDataSetChanged();
	}

	public boolean sort() {
		return super.sort(itemList.getItems());
	}
}
